package com.lzwork.gpt.db.entity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzwork.utility.logger.LOGGER;
import com.lzwork.utility.pair.Pair;
import com.lzwork.utility.pair.StringPair;
import com.lzwork.utility.str.StrUtility;
import com.lzwork.web.JsonKey;
import com.lzwork.web.data.BoolResultInfo;

import lombok.Getter;
import lombok.Setter;

/**
 * @author LiZheng
 * @date 2023年12月11日 下午4:58:15
 */

@Getter
@Setter
public class ApiEditEntity implements Serializable
{
	private static final long serialVersionUID = 1L;

	int id;
	String paramDemo;
	int promptUh;
	int promptSh;

	Map<String, String> paramDemoMap = new HashMap<>();

	public void refreshParam()
	{
		JSONObject vObj = null;
		paramDemoMap.clear();

		if (StrUtility.stringValid(paramDemo))
		{
			try
			{
				vObj = JSONObject.parseObject(paramDemo);

				for (Entry<String, Object> e : vObj.entrySet())
				{
					String key = e.getKey();
					String v = e == null ? "" : e.getValue().toString();
					paramDemoMap.put(key, v);
				}
			} catch (Exception e)
			{
				LOGGER.warn(LOGGER.PARSE, "Parse parameter default data fail: " + e.getMessage());
				vObj = null;
			}
		}
	}

	public BoolResultInfo setParams(List<StringPair> input)
	{
		List<String> errLog = new ArrayList<>();
		HashMap<String, String> paramDefault = new LinkedHashMap<>();

		for (StringPair sp : input)
		{
			String key = sp.first();

			Pair<String, List<Character>> after = JsonKey.jsonKeyFilter(key);

			List<Character> invalids = after.second();

			if (!after.second().isEmpty())
			{
				errLog.add("Key {" + key + "} contains invalid characters: " + invalids);
				key = after.first();
			}

			if (StrUtility.stringValid(sp.second()))
				paramDefault.put(key, sp.second());
		}

		paramDemo = JSON.toJSONString(paramDefault);

		if (errLog.isEmpty())
			return BoolResultInfo.makeTrue("");

		return BoolResultInfo.makeFalse(errLog);
	}
}
